package com.geek2.supermarket.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@Configuration
public class SysInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
          System.out.println("中文中文中文中文中文中文, preHandle......");
/*        //获取请求的url
        String url = request.getRequestURI();
        //判断url是否公开地址（实际使用时将公开地址配置到配置文件中）
        //这里假设公开地址是否登陆提交的地址
        if(url.indexOf("login") > 0) {
            //如果进行登陆提交，放行
            System.out.println("=======登陆放行");
            return true;
        }*/

        HttpSession session = request.getSession();
        //从session中取出用户身份信息
        String username = (String) session.getAttribute("username");
        if (username != null) {
            System.out.println("拦截器，用户已登录" + username);
            return true;
        }
        //执行到这里表示用户身份需要验证，跳转到登陆页面
        request.setAttribute("error","请先登录");
        request.getRequestDispatcher("/index.jsp").forward(request, response);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("中文中文中文中文中文中文, postHandle......");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("中文中文中文中文中文中文, afterConcurrentHandlingStarted......");
    }
}